package logic

import (
	"context"
	"fmt"
	"market/model/mysql"
	"market/model/redis"
	"market/pkg"

	"market/marketrpc/internal/svc"
	"market/marketrpc/marketrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserUpdateLogic) UserUpdate(in *marketrpc.UserUpdateRequest) (*marketrpc.UserUpdateResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("Smsupdate" + in.Phone)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("当前短信验证码输入错误")
	}

	var finduser mysql.User
	mysql.DB.Debug().Where("phone =?", in.Phone).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册")
	}

	if finduser.Password != pkg.Md5Password(in.Oldpassword) {
		return nil, fmt.Errorf("当前老密码输入错误")
	}

	if finduser.Password == pkg.Md5Password(in.Password) {
		return nil, fmt.Errorf("老密码与新密码不能一致")
	}
	if pkg.Md5Password(in.Password) != pkg.Md5Password(in.Newpassword) {
		return nil, fmt.Errorf("新密码确认失败")
	}
	finduser.Password = pkg.Md5Password(in.Password)
	mysql.DB.Debug().Updates(&finduser)
	redis.Client.Del("Smsupdate" + in.Phone)
	return &marketrpc.UserUpdateResponse{Id: int64(finduser.ID)}, nil
}
